package com.epoint.arcsoftface.acty;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Point;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epoint.arcsoftface.R;
import com.epoint.arcsoftface.presenter.FaceLiveDetectPresenter;
import com.epoint.arcsoftface.view.FaceCompareView;
import com.epoint.common.camera.CameraHelper;
import com.epoint.core.util.easythread.AsyncCallback;
import com.epoint.core.util.task.FrmAsynTask;
import com.epoint.ui.baseactivity.FrmBaseActivity;
import com.epoint.ui.widget.toast.ToastUtil;
import com.google.gson.JsonObject;

import java.util.concurrent.Callable;


/**
 * 作者： zhangj
 * 创建时间： 2020/2/6 10:11
 * 版权： 江苏国泰新点软件有限公司
 * 版本： [1.0 2020/2/6 ]
 * 描述：活体人脸信息采集
 */
public class FaceCaptureActivity extends FrmBaseActivity implements FaceCompareView {
    SurfaceView cameraView;   //摄像头画面

    LinearLayout llLoginResult;   //左边的显示的登录结果框

    TextView tvLoginResult;      //登录结果信息展示

    TextView tvLoginTips;        //登录结果下一步操作提示

    ImageView ivInit;

    private CameraHelper cameraHelper;  //摄像头操作类

    Handler compareHandler = new Handler();

    volatile boolean initSuccess = false;

    volatile boolean compareSuccess = false;

    FrmAsynTask task = new FrmAsynTask();  //初始化授权 放到线程里执行，防止卡死

    TextView tvCountView;

    MyCountDownTimer mCountDownTimer;
    FaceLiveDetectPresenter presenter = null;

    int timeout = 30;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setLayout(R.layout.facedetect_activity);
        timeout = getIntent().getIntExtra("timeout",30);
        pageControl.getNbBar().hide();
        presenter = new FaceLiveDetectPresenter(this,pageControl);
        initView();
        initData();

    }

    /**
     * 初始化view
     */
    public void initView(){
        cameraView = findViewById(R.id.textureView);
        llLoginResult = findViewById(R.id.ll_login_result);
        tvLoginResult = findViewById(R.id.tv_login_result);
        tvLoginTips = findViewById(R.id.tv_login_tips);
        tvCountView = findViewById(R.id.start_skip_count_down);
        ivInit = findViewById(R.id.iv_init);
    }

    public void initData() {

        tvCountView.setText((timeout + 1)+"s");
        //创建倒计时类
        mCountDownTimer = new MyCountDownTimer(timeout * 1000, 1000);
        mCountDownTimer.start();

        cameraView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                cameraView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                task.start(new Callable() {
                    @Override
                    public Object call() throws Exception {
                        initSuccess = presenter.activeAndInit();
                        return initSuccess;
                    }
                }, new AsyncCallback() {
                    @Override
                    public void onSuccess(Object o) {

                    }

                    @Override
                    public void onFailed(Throwable throwable) {
                        initSuccess = false;
                    }
                });


                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                cameraHelper = new CameraHelper.Builder()
                        .previewViewSize(new Point(cameraView.getMeasuredWidth(), cameraView.getMeasuredHeight()))
                        .rotation(getWindowManager().getDefaultDisplay().getRotation())
                        .specificCameraId(0)
                        .isMirror(false)
                        .previewOn(cameraView)
                        .cameraListener(presenter)
                        .build();
                cameraHelper.init();
                cameraHelper.start();
            }
        });
    }





    public void delayCloseActivity() {
        //成功之后 1s后关闭
        compareHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.putExtra("code","-1");
                intent.putExtra("message","采集时间超时");
                setResult(RESULT_OK,intent);
                finish();
            }
        }, 2000);
    }


    @Override
    public void onPreview() {
        if (ivInit.getVisibility() == View.VISIBLE){
            ivInit.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null){
            presenter.detachView();
        }
        if (cameraHelper != null) {
            cameraHelper.release();
        }
        compareHandler.removeCallbacksAndMessages(null);
        if (mCountDownTimer != null){
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @Override
    public void refreshViewWithDetectSuccess(JsonObject obj) {
        if (!compareSuccess){
            compareSuccess = true;
            ToastUtil.toastShort(getContext(),"采集成功");
            Intent intent = new Intent();

            intent.putExtra("facebase64",obj.get("facebase64").getAsString());
            intent.putExtra("code","1");
            setResult(RESULT_OK,intent);
            finish();
        }

    }

    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture
         *      表示以「 毫秒 」为单位倒计时的总数
         *      例如 millisInFuture = 1000 表示1秒
         *
         * @param countDownInterval
         *      表示 间隔 多少微秒 调用一次 onTick()
         *      例如: countDownInterval = 1000 ; 表示每 1000 毫秒调用一次 onTick()
         *
         */

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }


        public void onFinish() {
            tvCountView.setText("0s");
            if (!compareSuccess) {
                delayCloseActivity();
            }else{
                Intent intent = new Intent();
                intent.putExtra("code","-1");
                intent.putExtra("message","采集超时");
                setResult(RESULT_OK,intent);
                finish();
            }
        }

        public void onTick(long millisUntilFinished) {
            tvCountView.setText( millisUntilFinished / 1000 + "s");
        }

    }
}
